<template>
  <div class="panel right-panel" :style="{
    width: width + 'px',
    // minWidth: '200px',
    // maxWidth: '350px'
  }" v-show="true">
    <div class="ai-header">AI助手</div>
    <div class="ai-chat">
      <div class="chat-message-wrapper" v-for="msg in chatMessages" :key="msg.id">
        <div :class="['chat-message', 'message-' + msg.type]">
          <strong>{{ msg.type === 'user' ? '你' : 'AI' }}：</strong>
          <pre class="message-content">{{ msg.content }}</pre>
        </div>
      </div>
      <div v-if="streamError" class="stream-error-message">
        {{ streamError }}
      </div>
    </div>
    <el-button @click="closePanel" class="button-right-close">
      关闭
    </el-button>
    <div class="panel-content">
      <div class="ai-input">
        <div class="input-group">
          <el-select v-model="modelSel" placeholder="模型切换" size="small" class="custom-change-btn">
            <el-option label="DeepSeek" value="deepseek-ai/DeepSeek-V3" :key="'deepseek-ai/DeepSeek-V3'"></el-option>
            <el-option label="通义千问" value="Qwen/Qwen3-8B" :key="'Qwen/Qwen3-8B'"></el-option>
          </el-select>
          <el-input
            v-model="chatInput"
            placeholder="输入问题..."
            clearable
            ref="inputRef"
            class="custom-input"
            @keyup.enter="isStreaming ? null : toggleStream()"
            :disabled="isStreaming"
          />
          <button
            @click="toggleStream"
            class="stream-action-button"
            :class="{ 'streaming': isStreaming }"
            :title="isStreaming ? '停止对话' : '发送消息'"
            ref="streamButtonRef"
          >
            <span v-if="!isStreaming">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
            </span>
            <span v-else>
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M6 18h12V6H6v12zM8 8h8v8H8V8z"></path></svg>
            </span>
          </button>
        </div>
      </div>
      <p>固定宽度: {{ width }}px</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, onUnmounted } from 'vue';
import { useEditorStore } from '@/stores/editStore';
// import { useAiChatStore } from '../../stores/aichatStroe'; // Removed if not used elsewhere
const editorStore = useEditorStore()
interface ChatMessage {
  id: string;
  type: 'user' | 'ai';
  content: string;
}

const props = defineProps({
  width: {
    type: Number,
    required: true
  },
  visible: {
    type: Boolean,
    required: true
  },
  initialMessages: {
    type: Array as () => string[], // Assuming string array for simplicity
    default: () => []
  }
});

const emit = defineEmits(['close', 'update:isAIOpen', 'messageSent', 'modelChanged']);

const chatInput = ref('');
const chatMessages = ref<ChatMessage[]>(
  props.initialMessages.map((msgStr, index) => {
    let type: 'user' | 'ai' = 'ai'; // Default
    let content = msgStr;
    if (msgStr.toLowerCase().startsWith("你：") || msgStr.toLowerCase().startsWith("user:")) {
      type = 'user';
      content = msgStr.substring(msgStr.indexOf('：') + 1).trim();
    } else if (msgStr.toLowerCase().startsWith("ai：") || msgStr.toLowerCase().startsWith("assistant:")) {
      type = 'ai';
      content = msgStr.substring(msgStr.indexOf('：') + 1).trim();
    }
    return { id: `initial-${index}-${Date.now()}`, type, content };
  })
);

const inputRef = ref<any>(null); // For el-input
const streamButtonRef = ref<HTMLButtonElement | null>(null); // For the new stream button
const modelSel = ref('deepseek-ai/DeepSeek-V3');

// --- Streaming Logic Refs ---
const isStreaming = ref(false);
const streamError = ref<string | null>(null);
const eventSource = ref<EventSource | null>(null);
let currentAiMessageId: string | null = null;
const aiChatContainerRef = ref<HTMLElement | null>(null); // For scrolling

// 同步输入框和按钮高度的函数
const syncInputButtonHeight = () => {
  nextTick(() => {
    if (inputRef.value && inputRef.value.$el && streamButtonRef.value) {
      const inputEl = inputRef.value.$el.querySelector('.el-input__inner') as HTMLElement;
      const btnEl = streamButtonRef.value;

      if (inputEl && btnEl) {
        const inputHeight = inputEl.offsetHeight;
        btnEl.style.height = `${inputHeight}px`;
        // Adjust padding if necessary, or ensure SVG scales well
        // btnEl.style.paddingTop = '0';
        // btnEl.style.paddingBottom = '0';
      }
    }
  });
};

const scrollToBottom = () => {
  nextTick(() => {
    const chatArea = document.querySelector('.ai-chat'); // More robust selector if needed
    if (chatArea) {
      chatArea.scrollTop = chatArea.scrollHeight;
    }
  });
};

// --- Stream Chat Functions ---
const startStream = async () => {
  //ruirui 测试了下取markdown格式文档
  const content = editorStore.getMarkdown()
  console.log(content)
  const userInput = "根据上下文："+content+"   请回答用户问题 ：" + chatInput.value.trim();
  if (!userInput) {
    streamError.value = '请输入您的问题。';
    return;
  }

  isStreaming.value = true;
  streamError.value = null;

  // Add user message
  chatMessages.value.push({ id: `user-${Date.now()}`, type: 'user', content: userInput });
  emit('messageSent', userInput);

  // Prepare for AI response
  currentAiMessageId = `ai-${Date.now()}`;
  chatMessages.value.push({ id: currentAiMessageId, type: 'ai', content: '' });
  chatInput.value = ''; // Clear input
  scrollToBottom();

  try {
    // IMPORTANT: Ensure your backend /api/chat/stream can handle the 'model' query parameter
    const streamUrl = `http://localhost:8080/api/chat/stream?model=${encodeURIComponent(modelSel.value)}&message=${encodeURIComponent(userInput)}`;
    eventSource.value = new EventSource(streamUrl);

    eventSource.value.onopen = () => {
      console.log("EventSource connection opened.");
      const aiMessageEntry = chatMessages.value.find(m => m.id === currentAiMessageId);
      if (aiMessageEntry && aiMessageEntry.content === '') {
        // Optionally add a slight delay or a "typing" indicator
      }
      scrollToBottom();
    };

    eventSource.value.onmessage = (event) => {
      const aiMessageEntry = chatMessages.value.find(m => m.id === currentAiMessageId);
      if (aiMessageEntry) {
        if (event.data === "[DONE]") {
          //   aiMessageEntry.content += `\n[对话正常结束]`; // Or just let it end naturally
          stopStreamInternally(); // Backend signals done
          return;
        }
        aiMessageEntry.content += event.data;
        scrollToBottom();
      }
    };

    eventSource.value.onerror = (errEvent) => {
      if (!isStreaming.value || !eventSource.value) {
        console.log("EventSource error ignored as streaming is already stopped or source is null.");
        return;
      }
      console.error('EventSource failed:', errEvent);
      let specificError = '连接错误，请检查服务端或网络。';
      if (eventSource.value && eventSource.value.readyState === EventSource.CLOSED) {
        specificError = '连接已丢失或被服务器关闭。';
      }
      streamError.value = specificError;
      const aiMessageEntry = chatMessages.value.find(m => m.id === currentAiMessageId);
      if (aiMessageEntry) {
        aiMessageEntry.content += `\n[错误: ${specificError}]`;
      }
      stopStreamInternally();
    };

  } catch (err: any) {
    console.error('Error starting stream:', err);
    streamError.value = '启动连接失败: ' + (err.message || '未知错误');
    const aiMessageEntry = chatMessages.value.find(m => m.id === currentAiMessageId);
    if (aiMessageEntry) {
      aiMessageEntry.content += `\n[启动错误: ${streamError.value}]`;
    }
    isStreaming.value = false;
    if (eventSource.value) {
      eventSource.value.close();
      eventSource.value = null;
    }
    currentAiMessageId = null;
  }
};

const stopStreamInternally = () => {
  if (eventSource.value) {
    eventSource.value.onopen = null;
    eventSource.value.onmessage = null;
    eventSource.value.onerror = null;
    eventSource.value.close();
    eventSource.value = null;
  }
  isStreaming.value = false;
  currentAiMessageId = null; // Clear current AI message context
  scrollToBottom();
};

const stopStreamUser = () => {
  if (isStreaming.value && eventSource.value) {
    streamError.value = '用户主动终止对话';
    const aiMessageEntry = chatMessages.value.find(m => m.id === currentAiMessageId);
    if (aiMessageEntry) {
      if(!aiMessageEntry.content.includes('[用户主动终止对话]')) {
        aiMessageEntry.content += `\n[用户主动终止对话]`;
      }
    } else if (!chatMessages.value.length || chatMessages.value[chatMessages.value.length-1].type === 'user') {
      // If AI hasn't responded yet, or last message was user's
      chatMessages.value.push({ id: `ai-aborted-${Date.now()}`, type: 'ai', content: '[用户主动终止对话]'})
    }
    stopStreamInternally();
  } else {
    isStreaming.value = false; // Ensure state is correct
    if (eventSource.value) {
      eventSource.value.close();
      eventSource.value = null;
    }
  }
};

const toggleStream = () => {
  if (isStreaming.value) {
    stopStreamUser();
  } else {
    startStream();
  }
};

// --- Lifecycle Hooks ---
watch(modelSel, (newValue) => {
  emit('modelChanged', newValue);
});

watch(chatMessages, scrollToBottom, { deep: true });


onMounted(() => {
  syncInputButtonHeight();
  window.addEventListener('resize', syncInputButtonHeight);
});

onUnmounted(() => {
  window.removeEventListener('resize', syncInputButtonHeight);
  if (eventSource.value) { // Clean up event source on unmount
    stopStreamInternally();
  }
});

const closePanel = () => { // Renamed from 'close' to avoid conflict if any
  emit('close');
};
</script>

<style scoped>
.panel {
  position: relative;
  background-color: #f0f2f5;
  border-left: 1px solid #dcdfe6;
  transition: width 0.3s ease;
  overflow: hidden; /* Changed from auto to hidden to prevent panel scrollbars */
  flex-shrink: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.ai-header {
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
  flex-shrink: 0;
}

.ai-chat {
  flex: 1;
  padding: 15px;
  overflow-y: auto; /* Enables scrolling for chat messages */
  min-height: 0; /* Important for flexbox scrolling */
  background-color: #fff; /* Optional: different background for chat area */
}

.chat-message-wrapper {
  margin-bottom: 10px;
}

.chat-message {
  padding: 8px 12px;
  border-radius: 6px;
  word-wrap: break-word; /* Ensure long words break */
  white-space: pre-wrap; /* Respect newlines and spaces */
}

.message-user {
  background-color: #d1e7dd; /* Light green for user */
  text-align: right; /* Align user messages to the right */
  margin-left: auto; /* Push to right */
  max-width: 80%;
}
.message-user .message-content {
  text-align: left; /* Content within user bubble left-aligned */
}


.message-ai {
  background-color: #f8f9fa; /* Light grey for AI */
  border: 1px solid #e9ecef;
  max-width: 80%;
}

/*.message-content {
  margin: 0; !* Reset pre margin *!
  font-family: inherit; !* Use panel's font *!
  font-size: 0.95em;
  line-height: 1.6;
}*/

.message-content {
  margin: 0; /* Reset pre margin */
  font-family: inherit; /* Use panel's font */
  font-size: 0.95em;
  line-height: 1.6;
  white-space: pre-wrap;   /* 确保保留空白和换行 */
  overflow-wrap: break-word; /* This allows unbreakable words to be broken if they would overflow */
  word-break: break-all; /* More aggressive word breaking if needed, especially for CJK text or long URLs. Consider if `overflow-wrap` is enough. */
}




.panel-content {
  flex-shrink: 0; /* Prevent this from shrinking */
}

.ai-input {
  padding: 15px;
  border-top: 1px solid #ddd;
}

.input-group {
  display: flex;
  align-items: stretch; /* Make items same height */
}

.custom-change-btn {
  width: auto; /* Let select define its own width or set fixed */
  min-width: 90px; /* Ensure enough space for label */
  margin-right: -1px; /* For connected border look with input */
}
.custom-change-btn .el-input__inner { /* Target el-select's input part */
  border-radius: 4px 0 0 4px!important;
}


.custom-input {
  flex: 1;
  /* margin-right: -1px; /* Eliminated by stream button style */
}

/* Ensure el-input takes up the middle space correctly */
.custom-input .el-input__inner {
  border-radius: 0 !important; /* Middle element, no border radius */
  /* border-left: none; /* Covered by select margin-right -1px */
  /* border-right: none; /* Covered by button margin-left -1px */
}

/* New Stream Button Styles */
.stream-action-button {
  /* width: 40px; /* Fixed width for the button */
  /* Height will be set by syncInputButtonHeight to match input */
  padding: 0 10px; /* Padding for the icon */
  background-color: #409eff; /* Default blue (start/send) */
  color: white;
  border: 1px solid #409eff; /* Match Element Plus button style */
  /* border-left: none; */ /* Connects to the input field */
  margin-left: -1px; /* Overlap border for connected look */
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.3s ease, transform 0.1s ease, border-color 0.3s ease;
  flex-shrink: 0;
  border-radius: 0 4px 4px 0; /* Rounded corners on the right */
}

.stream-action-button:hover {
  opacity: 0.9;
  background-color: #66b1ff;
  border-color: #66b1ff;
}
.stream-action-button:active {
  transform: scale(0.95);
}

.stream-action-button.streaming {
  background-color: #ff4d4f; /* Red (stop) */
  border-color: #ff4d4f;
}
.stream-action-button.streaming:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}


.stream-action-button svg {
  width: 18px; /* Slightly smaller icon to fit better */
  height: 18px;
}

.custom-input:focus-within {
  z-index: 1; /* Ensure focused input border is on top */
}
.stream-action-button:focus {
  z-index: 1;
}


.button-right-close {
  /* Consider placing close button in ai-header or outside panel-content for better layout */
  /* float: right; */ /* Float can be tricky with flexbox */
  position: absolute;
  top: 10px;
  right: 15px;
  /* margin-right: 20px; */
  /* margin-top: 20px; */
  background-color: rgb(147, 187, 187);
  z-index: 10; /* Ensure it's above other elements if needed */
}

.stream-error-message {
  color: #ff4d4f;
  margin-top: 10px;
  padding: 8px;
  background-color: rgba(255, 77, 79, 0.1);
  border: 1px solid rgba(255, 77, 79, 0.3);
  border-radius: 4px;
  font-size: 0.9em;
}

</style>
